package com.bobbygu.bobbyapp.view.loopviewpager

import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bobbygu.lib.mvvm.common.BaseActivity
import com.bobbygu.bobbyapp.R
import com.squareup.picasso.Picasso
import java.util.*

/**
 *
 * # time:   2017/10/23 10:42
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since 1.1.3
 */
class ADPagerAdapter(private val activity: BaseActivity<*, *>) : PagerAdapter() {
    private val imgList = ArrayList<String>()

    override fun getCount() = imgList.size

    override fun isViewFromObject(view: View, `object`: Any) = view === `object`

    override fun destroyItem(view: ViewGroup, position: Int, `object`: Any) {
        view.removeView(`object` as View)
    }

    override fun instantiateItem(itemView: ViewGroup, position: Int): Any {
        val view = ImageView(activity)
        view.setOnClickListener {
        }
        if (imgList.size > 0) {
            showImg(view, imgList[position % imgList.size])
        }
        view.scaleType = ImageView.ScaleType.CENTER_CROP

        itemView.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        return view
    }

    fun refreshItemList(list: ArrayList<String>) {
        imgList.clear()
        imgList.addAll(list)
        notifyDataSetChanged()
    }

    private fun showImg(iv: ImageView, url: String) {
        Picasso.with(activity)
                .load(url)
                .placeholder(R.drawable.home_ad_null)
                .error(R.drawable.home_ad_null)
                .into(iv)
    }
}
